<template>
  <div class="invoice-list">
    <!-- 筛选表单 -->
    <div class="filter-form">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline" style="text-align: left;">
        <el-form-item label="发票代码">
          <el-input v-model="filterForm.invoice_code" placeholder="请输入发票代码" clearable />
        </el-form-item>
        <el-form-item label="购买方名称">
          <el-input v-model="filterForm.buyer_name" placeholder="请输入购买方名称" clearable />
        </el-form-item>
        <el-form-item label="销售方名称">
          <el-input v-model="filterForm.seller_name" placeholder="请输入销售方名称" clearable />
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="filterForm.license_plate" placeholder="请输入车牌号" clearable />
        </el-form-item>
        <el-form-item label="开票日期范围">
          <el-date-picker
           type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增发票按钮 -->
    <div class="action-buttons filter-form">
      <el-button type="primary" @click="openCreateDialog">新增发票</el-button>
      <el-button type="primary" @click="openUploadDialog">批量上传</el-button>
    </div>

    <!-- 新增发票对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <InvoiceModel :formData="currentInvoice" :invoice_id="currentInvoice.id" @close="dialogVisible = false" />
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="uploadDialogVisible" width="70%">
      <UploadInvoiceModel @close="uploadDialogVisible = false" />
    </el-dialog>
    
    <!-- 发票列表 -->
    <el-table :data="invoiceList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="invoice_code" width="120" label="发票代码" />
      <el-table-column prop="invoice_number" label="发票号码" />
      <el-table-column prop="issue_date" label="开票日期" />
      <el-table-column prop="buyer_name" label="购买方名称" />
      <el-table-column prop="seller_name" label="销售方名称" />
      <el-table-column prop="item_name" label="项目名称" />
      <el-table-column prop="license_plate" label="车牌号" />
      <el-table-column prop="vehicle_type" label="车辆类型" />
      <el-table-column prop="amount" label="金额" />
      <el-table-column prop="tax" label="税额" />
      <el-table-column prop="total" label="合计" />
      <el-table-column prop="payee" label="收款人" />
      <el-table-column prop="issuer" label="开票人" />
      <el-table-column prop="created_at" label="创建时间" width="160" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="mini" @click="handleDownload(scope.row)">下载</el-button>
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>
  </div>
</template>

<script>
import { fetchInvoiceList,deleteInvoice } from '@/services/invoiceService';
import InvoiceModel from './InvoiceModel.vue';
import UploadInvoiceModel from './UploadInvoiceModel.vue';

export default {
  name: 'InvoiceList',
  components: {
    InvoiceModel,
    UploadInvoiceModel
  },
  data() {
    return {
      // 筛选表单
      filterForm: {
        invoice_code: '',
        buyer_name: '',
        seller_name: '',
        license_plate: '',
        dateRange: [],
      },
      // 发票列表数据
      invoiceList: [],
      dialogVisible: false,
      uploadDialogVisible: false,
      dialogTitle: '新增发票',
      currentInvoice: {},
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      dialogVisible:false
    };
  },
  methods: {
    // 筛选
    handleFilter() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    openCreateDialog() {
      this.dialogTitle = '新增发票';
      this.currentInvoice = {};
      this.dialogVisible = true;
    },

    openUploadDialog() {
      this.dialogTitle = '批量上传';
      this.uploadDialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑发票';
      this.currentInvoice = { ...row };
      this.dialogVisible = true;
    },
    handleDownload(row) {
      const url = "http://localhost:8000/"+row.source_file_path;
      const link = document.createElement('a');
      link.href = url;
      link.target = 'download';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleDelete(row) {
      this.$confirm('确定删除该发票吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteInvoice(row.id)
          .then(() => {
            this.$message.success('删除成功');
            this.fetchData();
          })
          .catch((error) => {
            this.$message.error(`删除失败: ${error.message}`);
          });
      });
    },
    // 获取数据
    async fetchData() {
      try {
        const { currentPage, pageSize } = this.pagination;
        const response = await fetchInvoiceList(currentPage, pageSize,this.filterForm);
        this.invoiceList = response.data;
        this.pagination.total = response.total;
        this.pagination.currentPage = response.page;
        this.pagination.pageSize = response.limit;
      } catch (error) {
        console.error('Error fetching invoice data:', error);
      }
    },
  },
  created() {
    this.fetchData();
  },
};
</script>

<style scoped>
.invoice-list {
  padding: 20px;
}
.filter-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>